package com.ly.feishu.service;

import com.ly.feishu.entity.dto.FeishuBatchGetIdResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 飞书用户
 *
 * @author LiuYang
 * @since 2025/8/14 22:39
 **/
@Service
public class FeishuUserService {

    @Value("${feishu.api.search-url}")
    private String SEARCH_USER_URL;

    @Autowired
    private FeishuTokenService tokenService; // 你之前获取 tenant_access_token 的服务

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 根据手机号获取用户的 open_id
     *
     * @param mobile 手机号，格式如 "+8613812345678"
     * @return open_id，如果未找到返回 null
     */
    public String getOpenIdByMobile(String mobile) {
        String token = tokenService.getTenantAccessToken();
        if (token == null || token.isEmpty()) {
            throw new RuntimeException("无法获取 tenant_access_token");
        }

        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);

        // 构建请求体：{"mobiles": ["+8613812345678"]}
        Map<String, Object> requestBody = new HashMap<>();
        List<String> mobiles = new ArrayList<>();
        mobiles.add(mobile);
        requestBody.put("mobiles", mobiles);
        requestBody.put("include_resigned", true);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<FeishuBatchGetIdResponse> response = restTemplate.postForEntity(
                    SEARCH_USER_URL,
                    entity,
                    FeishuBatchGetIdResponse.class
            );

            FeishuBatchGetIdResponse result = response.getBody();

            if (result != null && result.getCode() == 0) {
                FeishuBatchGetIdResponse.Data data = result.getData();
                if (data != null && data.getUser_list() != null && !data.getUser_list().isEmpty()) {
                    // 查找匹配手机号的用户
                    for (FeishuBatchGetIdResponse.Data.User user : data.getUser_list()) {
                        if (user.getMobile() != null && user.getMobile().equals(mobile)) {
                            System.out.println("找到用户 open_id: " + user.getUser_id());
                            return user.getUser_id();
                        }
                    }
                }
                System.out.println("未找到用户，手机号: " + mobile);
                return null;
            } else {
                System.err.println("飞书 batch_get_id 失败: " + (result != null ? result.getMsg() : "未知错误"));
                return null;
            }
        } catch (Exception e) {
            System.err.println("调用飞书 batch_get_id 接口异常: " + e.getMessage());
            throw new RuntimeException("查询用户 open_id 失败", e);
        }
    }

    public Map<String, String> getOpenIdByMobile(List<String> mobileList) {
        Map<String, String> resultMap = new HashMap<>();
        String token = tokenService.getTenantAccessToken();
        if (token == null || token.isEmpty()) {
            throw new RuntimeException("无法获取 tenant_access_token");
        }

        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("mobiles", mobileList);
        requestBody.put("include_resigned", true);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<FeishuBatchGetIdResponse> response = restTemplate.postForEntity(
                    SEARCH_USER_URL,
                    entity,
                    FeishuBatchGetIdResponse.class
            );

            FeishuBatchGetIdResponse result = response.getBody();

            if (result != null && result.getCode() == 0) {
                FeishuBatchGetIdResponse.Data data = result.getData();
                if (data != null && data.getUser_list() != null && !data.getUser_list().isEmpty()) {
                    // 查找匹配手机号的用户
                    for (FeishuBatchGetIdResponse.Data.User user : data.getUser_list()) {
                        System.out.println("找到用户 open_id: " + user.getUser_id());
                        resultMap.put(user.getMobile(), user.getUser_id());
                    }
                }
                return resultMap;
            } else {
                System.err.println("飞书 batch_get_id 失败: " + (result != null ? result.getMsg() : "未知错误"));
                return resultMap;
            }
        } catch (Exception e) {
            System.err.println("调用飞书 batch_get_id 接口异常: " + e.getMessage());
            throw new RuntimeException("查询用户 open_id 失败", e);
        }
    }
}
